package com.wpzf.zxhc.utils;

import com.aspose.words.License;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;

import java.io.*;
import java.util.List;

public class WordUnits {


    // 将 Word 文件转换为 PDF 并返回字节流
    public static ByteArrayOutputStream wordToPdfStream(String wordFilePath) throws Exception {
        // 设置 Aspose.Words 的 License
        String licenseStr = "<License><Data><Products><Product>Aspose.Total for Java</Product><Product>Aspose.Words for Java</Product></Products><EditionType>Enterprise</EditionType><SubscriptionExpiry>20991231</SubscriptionExpiry><LicenseExpiry>20991231</LicenseExpiry><SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber></Data><Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature></License>";
        ByteArrayInputStream licenseStream = new ByteArrayInputStream(licenseStr.getBytes());
        License license = new License();
        license.setLicense(licenseStream);

        // 读取 Word 文档
        com.aspose.words.Document doc = new com.aspose.words.Document(wordFilePath);

        // 创建字节输出流来保存 PDF
        ByteArrayOutputStream pdfOutputStream = new ByteArrayOutputStream();

        // 将 Word 文档保存为 PDF 到字节输出流中
        doc.save(pdfOutputStream, com.aspose.words.SaveFormat.PDF);

        // 返回字节输出流
        return pdfOutputStream;
    }

    // 将word转换为PDF并保存到指定路径
    public static void wordToPdf(String wordFilePath, String pdfFilePath) throws Exception {
        String s = "<License><Data><Products><Product>Aspose.Total for Java</Product><Product>Aspose.Words for Java</Product></Products><EditionType>Enterprise</EditionType><SubscriptionExpiry>20991231</SubscriptionExpiry><LicenseExpiry>20991231</LicenseExpiry><SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber></Data><Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature></License>";
        ByteArrayInputStream is = new ByteArrayInputStream(s.getBytes());
        License license = new License();
        license.setLicense(is);
        com.aspose.words.Document d = new com.aspose.words.Document(wordFilePath);
        d.save(pdfFilePath);
    }

    // 替换文本方法
    public static void replaceText(XWPFDocument document, String placeholder, String replacement) {
        for (XWPFParagraph paragraph : document.getParagraphs()) {
            for (XWPFRun run : paragraph.getRuns()) {
                String text = run.getText(0);
                if (text != null && text.contains(placeholder)) {
                    text = text.replace(placeholder, replacement);
                    run.setText(text, 0);
                }
            }
        }
    }

    // 替换表格中的占位符文本
    public static void replaceTablePlaceholders(XWPFDocument document, String placeholder, String replacementText) {
        // 获取所有表格
        List<XWPFTable> tables = document.getTables();

        for (XWPFTable table : tables) {
            // 遍历表格中的每一行
            for (XWPFTableRow row : table.getRows()) {
                // 遍历每一行中的单元格
                for (XWPFTableCell cell : row.getTableCells()) {
                    // 获取单元格中的所有段落
                    List<XWPFParagraph> paragraphs = cell.getParagraphs();

                    for (XWPFParagraph paragraph : paragraphs) {
                        // 获取段落中的所有runs
                        List<XWPFRun> runs = paragraph.getRuns();
                        StringBuilder cellText = new StringBuilder();
                        for (XWPFRun run : runs) {
                            cellText.append(run.getText(0));  // 拼接每个run中的文本
                        }

                        String replacedText = cellText.toString().replace(placeholder, replacementText);

                        if (!replacedText.equals(cellText.toString())) {
                            // 清除所有原来的文本
                            for (int i = runs.size() - 1; i >= 0; i--) {
                                paragraph.removeRun(i);
                            }
                            // 将替换后的文本重新写入
                            XWPFRun newRun = paragraph.createRun();
                            newRun.setText(replacedText);
                        }
                    }
                }
            }
        }
    }

    // 替换表格内占位符为图片的方法
    public static void replaceTextWithImageInTables(XWPFDocument document, String placeholder, String imagePath, int maxWidth, int maxHeight) {
        for (XWPFTable table : document.getTables()) {
            for (XWPFTableRow row : table.getRows()) {
                for (XWPFTableCell cell : row.getTableCells()) {
                    replaceTextWithImageInCell(cell, placeholder, imagePath, maxWidth, maxHeight);
                }
            }
        }
    }

    // 替换单元格内占位符为图片的方法
    public static void replaceTextWithImageInCell(XWPFTableCell cell, String placeholder, String imagePath, int maxWidth, int maxHeight) {
        try {
            for (XWPFParagraph paragraph : cell.getParagraphs()) {
                for (XWPFRun run : paragraph.getRuns()) {
                    String text = run.getText(0);
                    if (text != null && text.contains(placeholder)) {
                        text = text.replace(placeholder, "");
                        run.setText(text, 0);  // 清空占位符

                        // 插入图片
                        FileInputStream is = new FileInputStream(imagePath);
                        int width = Units.toEMU(maxWidth);  // 最大宽度
                        int height = Units.toEMU(maxHeight);  // 最大高度
                        run.addPicture(is, XWPFDocument.PICTURE_TYPE_PNG, imagePath, width, height);
                        is.close();
                    }
                }
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}
